class Sku < ApplicationRecord
  mount_uploader :avatar, BaseUploader
  
  belongs_to :spu

  has_many :sku_option_values, dependent: :destroy
  accepts_nested_attributes_for :sku_option_values

  has_many :option_values, through: :sku_option_values

  validates :name, presence: true
  validates :cost_price, presence: true, numericality: { greater_than: 0 }
  validates :sale_price, presence: true, numericality: { greater_than: 0 }
  validates :promotion_price, presence: true, numericality: { greater_than: 0 }
  validates :on_hand_count, presence: true, numericality: { greater_than_or_equal_to: 0,  only_integer: true }

  def option_value_selected? option_type_id, option_value_id
    selected = self.sku_option_values.where(option_type_id: option_type_id, option_value_id: option_value_id).first
    !selected.blank?
  end

  def self.is_exit? spu, new_sku_option_values
    if new_sku_option_values.blank?
      false
    else
      is_exit_sku_option_values = []
      new_sku_option_values.each do |new_sku_option_value|
        select_sku_option_values = SkuOptionValue.select(:sku_id).joins(:sku).where("skus.spu_id = ? AND option_type_id = ? AND option_value_id = ?", spu.id, new_sku_option_value[1]["option_type_id"], new_sku_option_value[1]["option_value_id"]).map(&:sku_id)
        if select_sku_option_values.count <= 0
          is_exit_sku_option_values = []
          break
        end
        if is_exit_sku_option_values.count <= 0
          is_exit_sku_option_values = select_sku_option_values
        else
          is_exit_sku_option_values = is_exit_sku_option_values & select_sku_option_values
        end
      end
      is_exit_sku_option_values.count > 0 ? true : false
    end
  end

  def update_option_values new_sku_option_values
    return if new_sku_option_values.blank?
    new_sku_option_values.each do |new_sku_option_value|
      old_sku_option_value = self.sku_option_values.where(option_type_id: new_sku_option_value[1]["option_type_id"]).first  
      if old_sku_option_value.blank?
        SkuOptionValue.create(sku_id: self.id, option_type_id: new_sku_option_value[1]["option_type_id"], option_value_id: new_sku_option_value[1]["option_value_id"])
      else
        old_sku_option_value.update_column("option_value_id", new_sku_option_value[1]["option_value_id"])
      end
    end
  end
  
end
